package com.smile.cloud.zkConfig.distributedLock.zk;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * zookeeper 客户端
 */
@Data
@Slf4j
public class ZookeeperClient {

    /**
     * zk 锁前缀
     */
    private final static String LOCKER_PREFIX = "/zk_lock/";

    /**
     * 睡眠时间
     */
    private static final int SLEEP_TIME = 1000;

    /**
     * 最多重试次数
     */
    private static final int MAX_RETRIES = 3;

    private String zookeeperServer;

    private String zookeeperLockPath;

    private CuratorFramework client;

    public ZookeeperClient(String zookeeperServer, String zookeeperLockPath) {
        this.zookeeperServer = zookeeperServer;
        this.zookeeperLockPath = zookeeperLockPath;
        if (StringUtils.isBlank(this.zookeeperLockPath)) {
            this.zookeeperLockPath = LOCKER_PREFIX;
        }
    }


    public void init() {
        this.client = CuratorFrameworkFactory
                .builder()
                .connectString(this.getZookeeperServer())
                .retryPolicy(new ExponentialBackoffRetry(SLEEP_TIME, MAX_RETRIES))
                .build();
        this.client.start();
    }

    public void destroy() {
        try {
            if (getClient() != null) {
                getClient().close();
            }
        } catch (Exception e) {
            log.error("stop zookeeper client error {}", e.getMessage());
        }
    }
}